package kr.co.sdworld.api.apns.repository.message;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kr.co.sdworld.api.apns.model.ApnsLogin;
import kr.co.sdworld.api.apns.model.ApnsMessage;
import kr.co.sdworld.api.apns.model.ApnsMessageExample;
import kr.co.sdworld.api.apns.model.mapper.ApnsMessageMapper;
import kr.co.sdworld.api.apns.model.mapper.ApnsMessageMapperCustom;
import kr.co.sdworld.common.util.generator.IDGenerator;
import kr.co.sdworld.webs.ServiceContext;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class ApnsMessageDaoImpl extends SqlSessionDaoSupport implements ApnsMessageDao 
{
	@Override
	public List<ApnsMessage> searchByAppId(int row, int page, String appId) 
	{
		ApnsMessageMapper mapper = getSqlSession().getMapper(ApnsMessageMapper.class);
		ApnsMessageExample example = new ApnsMessageExample();
		example.createCriteria()
		.andAppIdEqualTo( appId);
		example.setOrderByClause("BADGE DESC");
		List<ApnsMessage> result = mapper.selectByExample(example);
		return result;
	}
	
	@Override
	public ApnsMessage getLatestApnsMessageByMaxBadge(String appId) 
	{
		synchronized (appId) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("appId", appId);
			ApnsMessageMapperCustom mapper = getSqlSession().getMapper( ApnsMessageMapperCustom.class);
			ApnsMessage message = mapper.getLatestApnsMessageByMaxBadge( param);
			
			return message;
		}
	}
	
	@Override
	public void create(ApnsMessage apnsMessage) 
	{
		ApnsLogin login = (ApnsLogin)ServiceContext.getSession().getAttribute("login");
		apnsMessage.setObjId( IDGenerator.generate());
		apnsMessage.setRegId( login.getUserId());
		ApnsMessageMapper mapper = getSqlSession().getMapper(ApnsMessageMapper.class);
		mapper.insertSelective(apnsMessage);
	}
}
